<?php

namespace app\api\home;

use think\Cache;
use think\Session;
use app\example\model\CollectUser as userModel;

class Auth extends Base
{
    public function login()
    {
        if (!$this->checkReferer()) {
            return $this->apiReturn('非法请求', 1);
        }
        if (!request()->isPost()) {
            return $this->apiReturn('方法不存在', 1);
        }
        $tel = input('param.tel/d');
        $code = input('param.code/d');
        $msg = '';
        if ($this->checkSmsCode($tel, $code, $msg)) {
            $user = userModel::where('teltphone', $tel)->find();
            if (empty($user)) {
                $user = new userModel();
                $user->teltphone = $tel;
                $user->save();
            }
            $login_user = ['id' => $user->id, 'tel' => $tel];
            session('login_user', $login_user);

            return $this->apiReturn();
        }

        return $this->apiReturn($msg, 1);
    }

    public function logout()
    {
        if (!$this->checkReferer()) {
            return $this->apiReturn('非法请求', 1);
        }
        if (!request()->isPost()) {
            return $this->apiReturn('方法不存在', 1);
        }
        session('login_user', null);

        return $this->apiReturn();
    }

    private function checkSmsCode($tel, $code, &$msg)
    {
        $cacheKey = sprintf(config('login_sms_code_key'), $tel);
        $cacheCode = cache($cacheKey);
        if (empty($cacheCode)) {
            $msg = '验证码不存在';

            return false;
        }
        $timeDiff = time() - intval($cacheCode['time']);
        if ($timeDiff >= config('sms_code_valid_time')) {
            cache($cacheKey, null);
            $msg = '验证码已过期';

            return false;
        }
        if ($code != $cacheCode['code']) {
            $msg = '验证码不正确';

            return false;
        }
        cache($cacheKey, null);

        return true;
    }
}
